package xmu.crms.config.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

/**
 * 安全配置
 * @author status200
 * @date 2017/12/24
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                // 不需要使用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //放行所有Preflight请求
                //跨域请求会有两次，第一次为OPTIONS类型的请求，不带header
                //第二次才是正式的请求
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                //只允许绑定账号和登录匿名访问
                .antMatchers(HttpMethod.PUT,"/me").permitAll()
                .antMatchers(HttpMethod.GET,"/signin").permitAll()
                .antMatchers("/school").permitAll()
                .antMatchers("/avatar/*").permitAll()

                .anyRequest().authenticated()

                .and()

                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
